package com.dynamicthreadpool.core;

import java.util.AbstractQueue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 支持动态调整大小的基于数组的阻塞队列实现
 * 扩展自BlockingQueue接口，实现了ResizeableBlockingQueue接口
 */
public class ResizeableArrayBlockingQueue<E> extends AbstractQueue<E> 
        implements BlockingQueue<E>, ResizeableBlockingQueue<E> {
    
    private static final long serialVersionUID = 1L;
    
    // 队列元素数组
    private volatile Object[] items;
    
    // 队列头部索引
    private int takeIndex;
    
    // 队列尾部索引
    private int putIndex;
    
    // 队列中元素数量
    private int count;
    
    // 主要锁，用于保护队列的修改
    private final ReentrantLock lock;
    
    // 用于阻塞等待的条件
    private final Condition notEmpty;
    private final Condition notFull;
    
    /**
     * 创建指定初始容量的队列
     * @param capacity 初始容量
     * @throws IllegalArgumentException 如果容量小于1
     */
    public ResizeableArrayBlockingQueue(int capacity) {
        if (capacity < 1) {
            throw new IllegalArgumentException("Queue capacity must be at least 1");
        }
        this.items = new Object[capacity];
        this.lock = new ReentrantLock();
        this.notEmpty = lock.newCondition();
        this.notFull = lock.newCondition();
    }
    
    /**
     * 创建指定初始容量并可选公平策略的队列
     * @param capacity 初始容量
     * @param fair 是否使用公平策略
     * @throws IllegalArgumentException 如果容量小于1
     */
    public ResizeableArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity < 1) {
            throw new IllegalArgumentException("Queue capacity must be at least 1");
        }
        this.items = new Object[capacity];
        this.lock = new ReentrantLock(fair);
        this.notEmpty = lock.newCondition();
        this.notFull = lock.newCondition();
    }
    
    /**
     * 从集合中创建队列
     * @param c 源集合
     * @throws IllegalArgumentException 如果集合为null或大小为0
     */
    public ResizeableArrayBlockingQueue(Collection<? extends E> c) {
        this(c.size());
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            int i = 0;
            try {
                for (E e : c) {
                    checkNotNull(e);
                    items[i++] = e;
                }
            } catch (ArrayIndexOutOfBoundsException ex) {
                throw new IllegalStateException("Collection size exceeds queue capacity");
            }
            count = c.size();
            putIndex = (i == items.length) ? 0 : i;
        } finally {
            lock.unlock();
        }
    }
    
    // 检查元素是否为null
    private static void checkNotNull(Object v) {
        if (v == null) {
            throw new NullPointerException();
        }
    }
    
    // 计算下一个索引位置
    private int inc(int i) {
        return (++i == items.length) ? 0 : i;
    }
    
    // 提取指定索引的元素
    @SuppressWarnings("unchecked")
    private E itemAt(int i) {
        return (E) items[i];
    }
    
    // 插入元素到队列
    private void insert(E x) {
        items[putIndex] = x;
        putIndex = inc(putIndex);
        ++count;
        notEmpty.signal();
    }
    
    // 从队列移除元素
    private E extract() {
        final Object[] items = this.items;
        E x = itemAt(takeIndex);
        items[takeIndex] = null;
        takeIndex = inc(takeIndex);
        --count;
        notFull.signal();
        return x;
    }
    
    @Override
    public boolean add(E e) {
        if (offer(e)) {
            return true;
        } else {
            throw new IllegalStateException("Queue full");
        }
    }
    
    @Override
    public boolean offer(E e) {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count == items.length) {
                return false;
            } else {
                insert(e);
                return true;
            }
        } finally {
            lock.unlock();
        }
    }
    
    @Override
    public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length) {
                notFull.await();
            }
            insert(e);
        } finally {
            lock.unlock();
        }
    }
    
    @Override
    public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
        checkNotNull(e);
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length) {
                if (nanos <= 0) {
                    return false;
                }
                nanos = notFull.awaitNanos(nanos);
            }
            insert(e);
            return true;
        } finally {
            lock.unlock();
        }
    }
    
    @Override
    public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (count == 0) ? null : extract();
        } finally {
            lock.unlock();
        }
    }
    
    @Override
    public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0) {
                notEmpty.await();
            }
            return extract();
        } finally {
            lock.unlock();
        }
    }
    
    @Override
    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0) {
                if (nanos <= 0) {
                    return null;
                }
                nanos = notEmpty.awaitNanos(nanos);
            }
            return extract();
        } finally {
            lock.unlock();
        }
    }
    
    @Override
    public E peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (count == 0) ? null : itemAt(takeIndex);
        } finally {
            lock.unlock();
        }
    }
    
    @Override
    public int size() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return count;
        } finally {
            lock.unlock();
        }
    }
    
    @Override
    public int remainingCapacity() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return items.length - count;
        } finally {
            lock.unlock();
        }
    }
    
    @Override
    public boolean remove(Object o) {
        if (o == null) {
            return false;
        }
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            final Object[] items = this.items;
            final int len = items.length;
            
            // 从takeIndex开始查找
            for (int i = takeIndex, k = 0; k < count; i = inc(i), k++) {
                if (o.equals(items[i])) {
                    removeAt(i);
                    return true;
                }
            }
            return false;
        } finally {
            lock.unlock();
        }
    }
    
    @Override
    public boolean contains(Object o) {
        if (o == null) {
            return false;
        }
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            final Object[] items = this.items;
            for (int i = takeIndex, k = 0; k < count; i = inc(i), k++) {
                if (o.equals(items[i])) {
                    return true;
                }
            }
            return false;
        } finally {
            lock.unlock();
        }
    }
    
    @Override
    public int drainTo(Collection<? super E> c) {
        return drainTo(c, Integer.MAX_VALUE);
    }
    
    @Override
    public int drainTo(Collection<? super E> c, int maxElements) {
        checkNotNull(c);
        if (c == this) {
            throw new IllegalArgumentException("Cannot drain to self");
        }
        if (maxElements <= 0) {
            return 0;
        }
        
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            int n = Math.min(maxElements, count);
            for (int i = 0; i < n; i++) {
                c.add(extract());
            }
            return n;
        } finally {
            lock.unlock();
        }
    }
    
    // 移除指定位置的元素
    private void removeAt(final int removeIndex) {
        final Object[] items = this.items;
        
        // 如果移除的是takeIndex位置，直接提取
        if (removeIndex == takeIndex) {
            items[takeIndex] = null;
            takeIndex = inc(takeIndex);
        } else {
            // 否则需要移动元素
            for (int i = removeIndex, next = inc(i); 
                 next != putIndex; 
                 i = next, next = inc(next)) {
                items[i] = items[next];
            }
            items[putIndex = dec(putIndex)] = null;
        }
        --count;
        notFull.signal();
    }
    
    // 计算上一个索引位置
    private int dec(int i) {
        return ((i == 0) ? items.length : i) - 1;
    }
    
    @Override
    public Iterator<E> iterator() {
        return new Itr();
    }
    
    // 迭代器实现
    private class Itr implements Iterator<E> {
        private int remaining;
        private int nextIndex;
        private E nextItem;
        private E lastItem;
        private int lastRet;
        
        Itr() {
            final ReentrantLock lock = ResizeableArrayBlockingQueue.this.lock;
            lock.lock();
            try {
                remaining = count;
                if (remaining > 0) {
                    nextIndex = takeIndex;
                    nextItem = itemAt(nextIndex);
                }
            } finally {
                lock.unlock();
            }
        }
        
        @Override
        public boolean hasNext() {
            return remaining > 0;
        }
        
        @Override
        public E next() {
            final ReentrantLock lock = ResizeableArrayBlockingQueue.this.lock;
            lock.lock();
            try {
                if (remaining == 0) {
                    throw new NoSuchElementException();
                }
                lastRet = nextIndex;
                lastItem = nextItem;
                
                // 计算下一个位置
                nextIndex = inc(nextIndex);
                --remaining;
                
                // 预先加载下一个元素
                if (remaining > 0) {
                    nextItem = itemAt(nextIndex);
                } else {
                    nextItem = null;
                }
                return lastItem;
            } finally {
                lock.unlock();
            }
        }
        
        @Override
        public void remove() {
            if (lastRet == -1) {
                throw new IllegalStateException();
            }
            final ReentrantLock lock = ResizeableArrayBlockingQueue.this.lock;
            lock.lock();
            try {
                removeAt(lastRet);
                // 调整迭代器状态
                if (lastRet < nextIndex) {
                    nextIndex = dec(nextIndex);
                }
                lastRet = -1;
            } finally {
                lock.unlock();
            }
        }
    }
    
    // 实现ResizeableBlockingQueue接口的方法
    @Override
    public boolean resize(int newCapacity) {
        if (newCapacity < 1) {
            throw new IllegalArgumentException("New capacity must be at least 1");
        }
        
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            int oldCapacity = items.length;
            if (newCapacity == oldCapacity) {
                return true; // 容量相同，无需调整
            }
            
            // 创建新数组
            Object[] newItems = new Object[newCapacity];
            
            // 复制元素到新数组
            for (int i = 0, k = takeIndex; i < count; i++, k = inc(k)) {
                newItems[i] = items[k];
            }
            
            // 更新队列状态
            items = newItems;
            takeIndex = 0;
            putIndex = (count == newCapacity) ? 0 : count;
            
            // 如果新容量大于旧容量，需要唤醒等待线程
            if (newCapacity > oldCapacity) {
                notFull.signalAll();
            }
            
            return true;
        } finally {
            lock.unlock();
        }
    }
    
    @Override
    public int capacity() {
        return items.length;
    }
    
    @Override
    public Object[] toArray() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] a = new Object[count];
            int k = takeIndex;
            for (int i = 0; i < count; i++, k = inc(k)) {
                a[i] = items[k];
            }
            return a;
        } finally {
            lock.unlock();
        }
    }
    
    @Override
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (a.length < count) {
                a = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), count);
            }
            
            int k = takeIndex;
            for (int i = 0; i < count; i++, k = inc(k)) {
                a[i] = (T) items[k];
            }
            
            if (a.length > count) {
                a[count] = null;
            }
            
            return a;
        } finally {
            lock.unlock();
        }
    }
    
    @Override
    public String toString() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            int k = takeIndex;
            int size = count;
            StringBuilder sb = new StringBuilder();
            sb.append('[');
            for (int i = 0; i < size; i++) {
                Object e = items[k];
                sb.append(e == this ? "(this Collection)" : e);
                k = inc(k);
                if (i < size - 1) {
                    sb.append(", ");
                }
            }
            sb.append(']');
            return sb.toString();
        } finally {
            lock.unlock();
        }
    }
}
